﻿using System;
using System.Media;
using System.Timers;
using System.Windows;
using System.Windows.Media.Animation;
namespace LiteLauncher.WIndow_Form
{
    /// <summary>
    /// NotificationWindow.xaml 的交互逻辑
    /// </summary>
    public partial class NotificationWindow : Window
    {
        private Timer _timer;
        private bool _isClosing = false;

        public event EventHandler ClosedByUser;

        // 添加 displayDuration 和 sound 参数
        public NotificationWindow(string title, string subtitle, string content, EventHandler onClose, int displayDuration = 3000, SystemSound sound = null)
        {
            InitializeComponent();
            TitleTextBlock.Text = title;
            SubtitleTextBlock.Text = subtitle;
            ContentTextBlock.Text = content;

            if (onClose != null)
            {
                ClosedByUser += onClose;
            }

            // 播放声音提示（如果提供了声音）
            sound?.Play();

            ShowAndHideNotification(displayDuration);
        }

         private void ShowAndHideNotification(int displayDuration)
        {
            // 设置初始位置（在屏幕右下角外）
            this.Left = SystemParameters.WorkArea.Width; // 初始位置在屏幕右侧之外
            this.Top = SystemParameters.WorkArea.Height - this.Height;

            // 创建显示动画
            DoubleAnimation showAnim = new DoubleAnimation(
                SystemParameters.WorkArea.Width,
                SystemParameters.WorkArea.Width - this.Width, // 最终位置在屏幕内
                TimeSpan.FromSeconds(0.5));
            showAnim.Completed += (s, e) =>
            {
                // 在展示后一段时间隐藏
                StartHideTimer(displayDuration);
            };

            this.BeginAnimation(Window.LeftProperty, showAnim); // 使用 LeftProperty 而不是 TopProperty
        }

        private void StartHideTimer(int displayDuration)
        {
            _timer = new Timer(displayDuration);
            _timer.Elapsed += (sender, args) =>
            {
                Dispatcher.Invoke(() =>
                {
                    HideNotification();
                    _timer.Stop();
                });
            };
            _timer.Start();
        }

        private void HideNotification()
        {
            if (_isClosing) return;

            _isClosing = true;

            DoubleAnimation hideAnim = new DoubleAnimation(
                this.Top,
                SystemParameters.WorkArea.Height,
                TimeSpan.FromSeconds(0.5));
            hideAnim.Completed += (s, e) =>
            {
                this.Close();
                ClosedByUser?.Invoke(this, EventArgs.Empty);
            };
            this.BeginAnimation(Window.TopProperty, hideAnim);
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            ClosedByUser?.Invoke(this, e);

            // 清理定时器
            if (_timer != null)
            {
                _timer.Stop();
                _timer.Dispose();
            }
        }
    }
}